<html>
<head><title>King Chung Ho's calculator</title></head>
<body>

<h1>Calculator</h1>
(version 1.0 04/07/2012 by King Chung Ho <br/>
Please input your expression
<p>
<form method="GET">
<input type="text" name="inputExpr"><input type="submit" 
value="Calculate">
</form>
</p>

Notes:
<ol>
	<li> Basic calculation is supported. Left-associative operator: 
+,-,/,*</li>
	<li> Support integer(123) and real numbers(123.11). </li>
	<li> "Invalid input expression" will be shown if invalid input 
is made. </li>
</ol>

<?php
//Turn off the warning
//error_reporting(E_WARNING | E_PARSE | E_ERROR);
error_reporting(0);
	if ($_GET["inputExpr"]){
		print "<p>";
		print "<h2>"."RESULT"."<BR/>"."</h2>";

		//check if there is any wrong input statement
		$expression=$_GET["inputExpr"];
		
		//check non-supportting characters
		$a=preg_match("#[^0-9\+\-\/\*\.]#",$expression);	
		//check if started by operators, * and /
		$b=preg_match("#^[(\*)(\/)]#",$expression);
		//check if ended by any operators
		$c=preg_match("#[(\*)(\/)(\+)(\-)(\.)]$#",$expression);
		//check if some conditions exist
		$d=preg_match("#[\*\/]{2,}#",$expression);
		$h=preg_match("#[\+\-]{3,}#",$expression);
		//check if double +, - or . occurs
		$e=preg_match("#[\-]{2,}#",$expression);
		$f=preg_match("#[\.]{2,}#",$expression);
		$g=preg_match("#[\+]{2,}#",$expression);

		if (($a==1) || ($b==1) || ($c==1) || ($d==1) || 
($e==1) || ($f==1) ||($g==1) || ($h==1)){
			print "Invalid input expression 
".$expression."<BR/>";
		}else{
			eval("\$ans=$expression;");
			print $expression." = ".$ans."<BR/>";
		}
		print "</p>";
	}
?>
</body>
</html>
